package forcollege.xly.com.xian.base;


import forcollege.xly.com.xian.net.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by xuleyuan on 2018/8/9
 */

public abstract class BasePresenter<I extends BaseInterface, R extends BaseData> {

    I baseInterface;

    Request<R> request;

    HashMap<String, Object> params;

    Class<R> mClass;

    public abstract Request<R> createRequest();

    public abstract void onGetResult(R data);

    public BasePresenter putParams(String key, Object value) {
        if (params == null) {
            params = new HashMap<>();
        }
        params.put(key, value);
        return this;
    }

    public void clearParams() {
        params = new HashMap<>();
    }

    protected BasePresenter() {
        Type type = getClass().getGenericSuperclass();
        Type trueType = ((ParameterizedType) type).getActualTypeArguments()[1];
        mClass = (Class<R>) trueType;
        request = createRequest();//在构造函数的时候吧我们创建的Request赋值给request对象

    }

    public void attach(I baseInterface) {
        this.baseInterface = baseInterface;
    }

    public I getBaseInterface() {
        return baseInterface;
    }

    public void detch() {
        this.baseInterface = null;
    }

    public void doRequest() {
        request.setmClass(mClass);
        request.setParams(params);
        request.doRequest().observeOn(AndroidSchedulers.mainThread()).subscribe(this::onGetResult);//Rxjava获取到数据，并且将结果传入onGerResult，这是简易的lambda写法
    }

}
